<?php

//在文章Post中定义与评论的关联关系,一对多，一片文章有多个评论
public function comments(){
  return $this->hasMany('App\Comment')->orderBy('created_at','desc');
}
//在评论模型中定义评论所属文章
public function post(){
  return $this->belongsTo('App\Post');
}

//评论路由
Route::post('/posts/{post}/comment','CommentController@comment');

public function comment(Request $request,Post $post){

     //验证
     $this->validate($request,[
       'content'=>'required|min:5'
     ]);

     //逻辑
      $comment = new Comment();
      $comment->user_id = Auth::id();
      $comment->content = $request->input('content');
      $post->comments()->save($comment);

     //渲染
     return back();
}


//预加载两种方法
$post = Post::with('comments')->get()
$post->load('comments');
//在模板中
@foreach ($post->comments as $comment) 
    
@endforeach




//如何获取当前文章所有的评论数
$posts = Post::withCount('comments')->get()
//在模板中
{{$post->comments_count}}
